package com.easpeed.elevator.utils

import android.annotation.SuppressLint
import android.content.Context
import android.graphics.Color
import android.view.Gravity
import android.view.View
import android.widget.ArrayAdapter
import android.widget.AutoCompleteTextView
import android.widget.EditText
import android.widget.TextView
import androidx.core.content.ContextCompat
import com.blankj.utilcode.util.ScreenUtils
import com.blankj.utilcode.util.SizeUtils
import com.blankj.utilcode.util.ToastUtils
import com.easpeed.comon.bean.OtdrBean
import com.easpeed.comon.consts.ConstsOpticalData
import com.easpeed.comon.utils.SelectorUtils
import com.easpeed.elevator.R
import com.easpeed.elevator.bean.EventThreshold
import com.google.android.flexbox.FlexboxLayout

/**
 * Created by bigyu on 2025-01-23 13:32
 * com.easpeed.elevator.utils
 */
class OpticalTestHelper(val mContext: Context) {
    //    dvs事件阈值
    private var currentSjzu: String = "100"

    //    dvs滤波
    private var currentLb: String = "100"

    //    dvs脉冲宽度
    private var currentMcsjDvs: String = "100"

    //    otdr数据
    //    采集范围
    private var currentCjfw: String = "10000"

    //    脉冲宽度
    private var currentMckd: String = "100"

    //    测试时间
    private var currentCssj: String = "5"

    // 波长
    private var currentBc: String = ConstsOpticalData.getDefaultBcKey()

    private val radius = 3f
    private var holder: OpticalViewHolder? = null


    fun setHolder(holder: OpticalViewHolder) {
        this.holder = holder
        initView()
        initListener()
    }

    @SuppressLint("SetTextI18n")
    private fun initListener() {
//        时序图
        holder?.singlePointTimeView?.apply {
            setOnClickListener {
                this.isActivated = !this.isActivated
                holder?.layoutSinglePointTimeView?.visibility = if (this.isActivated) View.VISIBLE else View.GONE
            }
        }

        //滤波数据设置
        holder?.dvsDataView?.apply {
            setOnClickListener {
                val dataList = ConstsOpticalData.dataLb
                val setFunc = fun(str: String) {
                    setCurrentLb(str)
                }
                val showText = fun(str: String): String {
                    return str
                }
                val selectData = currentLb
                val title = "设置滤波"
                val save = fun(str: String) {
                    // 保存
                    saveCallBack.invoke()
                }

                extracted(title, dataList, showText, selectData, setFunc, save)
            }
        }
        //波长
        holder?.otdrBcView?.apply {
            setOnClickListener {
                val dataList = ConstsOpticalData.getBcList()
                val setFunc = fun(str: String) {
                    setCurrentBc(str)
                }
                val showText = fun(str: String): String {
                    return str
                }
                val selectData = currentBc
                val title = "设置波长"
                val save = fun(str: String) {
                    // 保存
                    saveCallBack.invoke()
                }

                extracted(title, dataList, showText, selectData, setFunc, save)
            }
        }
        //脉宽数据设置
        holder?.dvsWidthDataView?.apply {
            setOnClickListener {
                val dataList = ConstsOpticalData.dataMcsjDvs
                val setFunc = fun(str: String) {
                    setCurrentMcsjDvs(str)
                }
                val showText = fun(str: String): String {
                    return "${str}ns"
                }
                val selectData = currentMcsjDvs
                val title = "设置脉宽"
                val save = fun(str: String) {
                    saveCallBack.invoke()
                    // 保存
                }
                extracted(title, dataList, showText, selectData, setFunc, save)
            }
        }
        //阈值数据设置
        holder?.dvsThresholdDataView?.apply {
            setOnClickListener {
                val setFunc = fun(str: String) {
                    setCurrentSjzu(str)
                }
                val showText = fun(str: String): String {
                    return str
                }
                val selectData = currentSjzu
                val title = "设置阈值"
                val save = fun(str: String) {
                    // 保存
                    saveCallBack.invoke()

                }
                extractedInput(title, showText, selectData, setFunc, save)
            }
        }

        //采集数据设置
        holder?.otdrRangeDataView?.apply {
            setOnClickListener {
                val selectData = currentCjfw
                val dataList = ConstsOpticalData.dataCjfw
                val setFunc = fun(str: String) {
                    //脉宽数据设置
                    if (selectData != str) {
                        val list = ConstsOpticalData.getMckdData(str)
                        setCurrentMckd("${list.firstOrNull()}")
                    }
                    setCurrentCjfw(str)
                }
                val showText = fun(str: String): String {
                    val formattedValue = (str.toInt() / 1000.0).let {
                        if (it % 1.0 == 0.0) it.toInt().toString()  // 如果是整数，则去掉小数部分
                        else String.format("%.1f", it)  // 否则保留一位小数
                    }

                    return "${formattedValue}km"
                }
                val title = "设置采集范围"
                val save = fun(str: String) {
                    // 保存
                    saveCallBack.invoke()

                }
                extracted(title, dataList, showText, selectData, setFunc, save)
            }
        }

        //脉宽数据设置
        holder?.otdrWidthDataView?.apply {
            setOnClickListener {
                val dataList = ConstsOpticalData.getMckdData(currentCjfw)
                val setFunc = fun(str: String) {
                    setCurrentMckd(str)
                }
                val showText = fun(str: String): String {
                    return "${str}ns"
                }
                val selectData = currentMckd
                val title = "设置脉冲宽度"
                val save = fun(str: String) {
                    // 保存
                    saveCallBack.invoke()

                }
                extracted(title, dataList, showText, selectData, setFunc, save)
            }
        }
        //时间数据设置
        holder?.otdrTimeDataView?.apply {
            setOnClickListener {
                val dataList = ConstsOpticalData.dataCssj
                val setFunc = fun(str: String) {
                    setCurrentCssj(str)
                }
                val showText = fun(str: String): String {
                    return "${str}s"
                }
                val selectData = currentCssj
                val title = "设置测试时间"
                val save = fun(str: String) {
                    // 保存
                    saveCallBack.invoke()
                }
                extracted(title, dataList, showText, selectData, setFunc, save)
            }
        }

    }

    private fun extracted(title: String, dataList: List<String>, showText: (String) -> String, selectData: String, setFunc: (String) -> Unit, save: (String) -> Unit) {
        var selectData1 = selectData
        showModify { dialog ->
            dialog.setText(R.id.title, title)
            val flexboxLayout = dialog.getViewT<FlexboxLayout>(R.id.layout_select)
            flexboxLayout.visibility = View.VISIBLE
            for (data in dataList) {
                val view = addViewFlexbox()
                view.text = showText(data)
                view.isActivated = data == selectData1
                view.setOnClickListener(View.OnClickListener { view1: View ->
                    for (i in 0 until flexboxLayout.childCount) {
                        flexboxLayout.getChildAt(i).isActivated = false
                    }
                    view1.isActivated = true
                    selectData1 = data
                })
                flexboxLayout.addView(view)
            }
            dialog.setOnclickListener(R.id.sure, View.OnClickListener { v: View? ->
                //改
                setFunc(selectData1)
                save(selectData1)
            })
        }
    }

    private fun extractedInput(title: String, showText: (String) -> String, selectData: String, setFunc: (String) -> Unit, save: (String) -> Unit) {
        showModify { dialog ->
            dialog.setText(R.id.title, title)
            val view = dialog.getViewT<EditText>(R.id.input)
            view.visibility = View.VISIBLE
            view.setText(showText(selectData))
            dialog.setOnclickListener(R.id.sure, View.OnClickListener { v: View? ->
                var data = view.text.toString().trim()
                if (data.isEmpty()) {
                    data = selectData
                }
                //改
                setFunc(data)
                save(data)
            })
        }
    }

    private fun showModify(render: (dialog: NoticeDialog) -> Unit) {
        val resID: Int = R.layout.dialog_select_optical
        val dialog = NoticeDialog.Builder(mContext).setLayoutId(resID).setClickBtnDismissDialog(true).setCanceledOnTouchOutside(false).create()
        dialog.setDialogWith(0, ScreenUtils.getScreenHeight())
        dialog.setGravity(Gravity.CENTER)
        dialog.show()
        render.invoke(dialog)
        dialog.setOnclickListener(R.id.cancel, View.OnClickListener { v: View? ->


        })
    }


    public fun showEventThreshold(title: String, defaultValue: EventThreshold?, callbackInterface: CallbackInterface<EventThreshold>) {
        val resID = R.layout.dialog_event_threshold_optical
        val dialog = NoticeDialog.Builder(mContext).setLayoutId(resID).setClickBtnDismissDialog(true).setCanceledOnTouchOutside(false).create()

        dialog.setDialogWith(0, ScreenUtils.getScreenHeight())
        dialog.setGravity(Gravity.CENTER)
        dialog.show()


        defaultValue?.let {
            dialog.setText(R.id.hsxs, it.hsxs.toString())
            dialog.setText(R.id.jsmx, it.jsmx.toString())
            dialog.setText(R.id.fsmx, it.fsmx.toString())
            dialog.setText(R.id.ffsmx, it.ffsmx.toString())
        }
        dialog.setText(R.id.title, title)
        dialog.setOnclickListener(R.id.sure, View.OnClickListener { v: View? ->
            try {
                val hsxs = dialog.getView(R.id.hsxs) as EditText
                val jsmx = dialog.getView(R.id.jsmx) as EditText
                val fsmx = dialog.getView(R.id.fsmx) as EditText
                val ffsmx = dialog.getView(R.id.ffsmx) as EditText
                val eventThreshold = EventThreshold(hsxs.text.toString().toFloat(), jsmx.text.toString().toFloat(), fsmx.text.toString().toFloat(), ffsmx.text.toString().toFloat())
                callbackInterface.onCallback(eventThreshold)
            } catch (e: Exception) {
                e.printStackTrace()
                ToastUtils.showShort("事件阈值数据出现错误")
            }
        })

        dialog.setOnclickListener(R.id.cancel, View.OnClickListener { v: View? -> })
    }

    private fun addViewFlexbox(): TextView {
        // 创建 TextView 实例
        val textView = TextView(mContext)
        // 设置 TextView 的属性
        textView.id = View.generateViewId()
        textView.layoutParams = FlexboxLayout.LayoutParams(0,  // 宽度 0dp，使用百分比宽度
            FlexboxLayout.LayoutParams.WRAP_CONTENT // 高度包裹内容
        )
        textView.setTextColor(Color.parseColor("#E5E6EB"))
        textView.gravity = Gravity.CENTER_VERTICAL
        // 设置 TextView 的 drawableStart
        val drawableStart = ContextCompat.getDrawable(mContext, R.drawable.shape_check_icon)
        textView.setCompoundDrawablesWithIntrinsicBounds(drawableStart, null, null, null)
        textView.compoundDrawablePadding = 2
        // 设置 MarginTop
        val params = textView.layoutParams as android.view.ViewGroup.MarginLayoutParams
        params.setMargins(0, SizeUtils.dp2px(10f), 0, 0)

        // 设置 FlexboxLayout 特定属性 (layout_flexBasisPercent)
        val layoutParams: FlexboxLayout.LayoutParams = textView.layoutParams as FlexboxLayout.LayoutParams
        layoutParams.flexBasisPercent = 0.2f // 设置为40%
        return textView
    }

    private fun initView() {
        holder?.wayView?.background = SelectorUtils.createSelector(mContext, Color.parseColor("#0E6FC9"), Color.parseColor("#D9D9D9"), radius)
        holder?.yhView?.background = SelectorUtils.createSelector(mContext, Color.parseColor("#0297D9"), Color.parseColor("#D9D9D9"), radius)
        holder?.otdrView?.background = SelectorUtils.createSelector(mContext, Color.parseColor("#0297D9"), Color.parseColor("#2B2B2B"), radius)

        holder?.otdrTimeView?.background = SelectorUtils.createSelector(mContext, Color.parseColor("#0297D9"), Color.parseColor("#0097DF"), radius)

        holder?.autoPeakView?.background = SelectorUtils.createSelector(mContext, Color.parseColor("#0297D9"), Color.parseColor("#05D7E4"), radius)
        holder?.manualPeakView?.background = SelectorUtils.createSelector(mContext, Color.parseColor("#0297D9"), Color.parseColor("#109FCA"), radius)

        //单点时序图
        holder?.singlePointTimeView?.background = SelectorUtils.createSelector(mContext, Color.parseColor("#D9D9D9"), Color.parseColor("#0297D9"), radius)
        //参数设置
        holder?.settingView?.background = SelectorUtils.createSelector(mContext, Color.parseColor("#0297D9"), Color.parseColor("#D3E1A8"), radius)

        holder?.otdrRangeDataView?.background = SelectorUtils.createSelector(mContext, Color.parseColor("#06CD91"), Color.parseColor("#06CD91"), radius)
        holder?.otdrWidthDataView?.background = SelectorUtils.createSelector(mContext, Color.parseColor("#A3BE3F"), Color.parseColor("#D3E1A8"), radius)
        holder?.otdrTimeDataView?.background = SelectorUtils.createSelector(mContext, Color.parseColor("#A3BE3F"), Color.parseColor("#A3BE3F"), radius)
        holder?.otdrHideView?.background = SelectorUtils.createSelector(mContext, Color.parseColor("#D9D9D9"), Color.parseColor("#06CD91"), radius)

        holder?.dvsDataView?.background = SelectorUtils.createSelector(mContext, Color.parseColor("#039BE1"), Color.parseColor("#039BE1"), radius)
        holder?.dvsWidthDataView?.background = SelectorUtils.createSelector(mContext, Color.parseColor("#02CBD5"), Color.parseColor("#02CBD5"), radius)
        holder?.dvsThresholdDataView?.background = SelectorUtils.createSelector(mContext, Color.parseColor("#A3C346"), Color.parseColor("#A3C346"), radius)
    }


    fun getDataBean(): OtdrBean {
        val otdrBean = OtdrBean()
        otdrBean.isDefaultSent = false
        //OTDR数据
        otdrBean.currentCjfw = currentCjfw
        otdrBean.currentMcsj = currentMckd
        otdrBean.currentCssj = currentCssj

        //            dvs数据
        otdrBean.currentMcsjDvs = currentMcsjDvs
        otdrBean.currentSjzu = currentSjzu
        otdrBean.currentLb = currentLb
        otdrBean.currentBc = currentBc
        return otdrBean
    }

    @SuppressLint("SetTextI18n")
    fun setCurrentSjzu(sjzu: String) {
        this.currentSjzu = sjzu
        holder?.dvsThresholdDataView?.text = "阈值\n${sjzu}"
    }

    @SuppressLint("SetTextI18n")
    fun setCurrentLb(lb: String) {
        this.currentLb = lb
        holder?.dvsDataView?.text = "滤波\n${lb}"
    }

    fun setCurrentBc(bc: String) {
        this.currentBc = bc
        holder?.otdrBcView?.text = "波长\n${bc}"
    }

    @SuppressLint("SetTextI18n")
    fun setCurrentMcsjDvs(mcsjDvs: String) {
        this.currentMcsjDvs = mcsjDvs
        holder?.dvsWidthDataView?.text = "脉宽\n${mcsjDvs}ns"
    }


    /**
     * 设置dvs数据
     * @param sjzu 阈值
     * @param lb 滤波
     * @param mcsjDvs 脉宽
     */
    fun setDvsData(sjzu: String, lb: String, mcsjDvs: String) {
        setCurrentSjzu(sjzu)
        setCurrentLb(lb)
        setCurrentMcsjDvs(mcsjDvs)
    }

    @SuppressLint("DefaultLocale")
    private fun setCurrentCjfw(cjfw: String) {
        this.currentCjfw = cjfw
        val formattedValue = (cjfw.toInt() / 1000.0).let {
            if (it % 1.0 == 0.0) it.toInt().toString()  // 如果是整数，则去掉小数部分
            else String.format("%.1f", it)  // 否则保留一位小数
        }
        holder?.otdrRangeDataView?.text = "范围\n${formattedValue}km"
    }

    @SuppressLint("SetTextI18n")
    fun setCurrentMckd(mcsj: String) {
        this.currentMckd = mcsj
        holder?.otdrWidthDataView?.text = "脉宽\n${mcsj}ns"
    }

    @SuppressLint("SetTextI18n")
    fun setCurrentCssj(cssj: String) {
        this.currentCssj = cssj
        holder?.otdrTimeDataView?.text = "时间\n${cssj}s"
    }

    fun getCurrentSjzu(): String {
        return currentSjzu
    }

    fun getCurrentLb(): String {
        return currentLb
    }

    fun getCurrentBc(): String {
        return currentBc
    }

    fun getCurrentMcsjDvs(): String {
        return currentMcsjDvs
    }

    fun getCurrentCjfw(): String {
        return currentCjfw
    }

    fun getCurrentMckd(): String {
        return currentMckd
    }

    fun getCurrentCssj(): String {
        return currentCssj
    }

    fun setOtdrData(currentCjfw: String, currentMckd: String, currentCssj: String, bc: String) {
        setCurrentCjfw(currentCjfw)
        setCurrentMckd(currentMckd)
        setCurrentCssj(currentCssj)
        setCurrentBc(bc)
    }


    private var saveCallBack: () -> Unit = {}
    fun saveCallBack(save: () -> Unit) {
        this.saveCallBack = save
    }

}


class OpticalViewHolder {


    //    dvs滤波数据
    var dvsDataView: TextView? = null

    //    dvs脉宽数据
    var dvsWidthDataView: TextView? = null

    //    dvs阈值数据
    var dvsThresholdDataView: TextView? = null

    var wayView: TextView? = null

    //余晖
    var yhView: TextView? = null

    //otdr测试
    var otdrView: TextView? = null

    //otdr时间表
    var otdrTimeView: TextView? = null


    // 波长
    var otdrBcView: TextView? = null

    //自动寻峰
    var autoPeakView: TextView? = null

    //手动寻峰
    var manualPeakView: TextView? = null

    //单点时序图
    var singlePointTimeView: TextView? = null
    var layoutSinglePointTimeView: View? = null

    //参数设置
    var settingView: TextView? = null

    //otdr范围
    var otdrRangeDataView: TextView? = null

    //    otdr脉宽
    var otdrWidthDataView: TextView? = null

    //    otdr时间
    var otdrTimeDataView: TextView? = null

    //    otdr隐藏
    var otdrHideView: TextView? = null

}